﻿using UnityEngine;
using System.Collections;

public class BackgroundTouch : MonoBehaviour, ITouchable
{

    private TeleportShotManager currentTeleportShot;

    private bool draggingBackground = false;
    private Vector3 lastTouchLocation = Vector3.zero;

    public bool IsDraggingBackground { get { return draggingBackground; } }

    public Vector3 CameraPosition { get; private set; }

    // Use this for initialization
    void Start()
    {
        TouchableList.Instance.AddItem(this);
        currentTeleportShot = null;

        FollowActionPriorityQueue.Instance.AddFollowPosition(new LevelSwipePrioritizedFollowPosition(this));
    }

    // Update is called once per frame
    void Update()
    {
        if (currentTeleportShot == null)
        {
            GameObject teleportShot = GameObject.FindGameObjectWithTag("teleportShot");
            if (teleportShot != null)
            {
                if (teleportShot.GetComponent<TeleportShotManager>() != null)
                {
                    currentTeleportShot = teleportShot.GetComponent<TeleportShotManager>();
                }
            }
        }
    }

    public void OnTouch(Vector3 screenPosition, Vector3 worldPosition)
    {
        GameObject teleportShot = GameObject.FindGameObjectWithTag("teleportShot");
        if (teleportShot != null)
        {
			print ("Teleport shot tag object named " + teleportShot.name + " found");
            teleportShot.GetComponent<TeleportShotManager>().FinishTeleport();
        }
        else
        {
            draggingBackground = true;
            lastTouchLocation = screenPosition;
        }
    }

    public bool HoldsTouch()
    {
        return true;
    }

    public void OnRelease(Vector3 screenPosition, Vector3 worldPosition)
    {
        draggingBackground = false;
    }

    public GameObject GetColliderObject()
    {
        return this.gameObject;
    }

    public void OnDrag(Vector3 screenPosition, Vector3 worldPosition)
    {
        if (draggingBackground)
        {
            Vector3 lastWorldPosition = Camera.main.ScreenToWorldPoint(lastTouchLocation);
            Vector3 moveDirection = worldPosition - lastWorldPosition;
            moveDirection.z = 0;
            Camera.main.transform.position -= moveDirection;
            CameraPosition = Camera.main.transform.position;
            lastTouchLocation = screenPosition;
        }
    }


    public bool TouchEnabled { get; set; }

    public void OnGUI()
    {
        if (draggingBackground)
        {
            Vector3 cameraScreen = Camera.main.WorldToScreenPoint(CameraPosition);
            Rect lookRect = new Rect(cameraScreen.x - 10, cameraScreen.y - 5, 20, 10);
            //print("Totally trying to show you where I'm looking, rect is " + lookRect);
            GUI.Label(lookRect, "####");
        }
    }
}
